package com.deductive.service.special.special_import.service;

import com.deductive.service.special.special_import.tool.AsyncTaskStatus;
import org.springframework.stereotype.Service;

import java.util.HashSet;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.ConcurrentHashMap;

@Service
public class TaskWorkflow {
    private final Map<String, Set<String>> taskDependencies = new ConcurrentHashMap<>();
    private final Map<String, Set<String>> dependentTasks = new ConcurrentHashMap<>();
    private final AsyncTaskManager asyncTaskManager;

    public TaskWorkflow(AsyncTaskManager asyncTaskManager) {
        this.asyncTaskManager = asyncTaskManager;
    }

    public void addDependency(String taskId, String dependsOnTaskId) {
        taskDependencies.computeIfAbsent(taskId, k -> new HashSet<>()).add(dependsOnTaskId);
        dependentTasks.computeIfAbsent(dependsOnTaskId, k -> new HashSet<>()).add(taskId);
    }

    public boolean canExecute(String taskId) {
        AsyncTaskStatus taskStatus = asyncTaskManager.getTaskStatus(taskId);
        if (taskStatus==null || "READY".equals(taskStatus.getStatus())){
            return false;
        }


        Set<String> dependencies = taskDependencies.get(taskId);
        if (dependencies == null || dependencies.isEmpty()) {
            return true;
        }

        for (String dependencyId : dependencies) {
            AsyncTaskStatus status = asyncTaskManager.getTaskStatus(dependencyId);
            if (status == null || !status.isCompleted()) {
                return false;
            }
        }
        return true;
    }

    public Set<String> getNextTasks(String completedTaskId) {
        return dependentTasks.getOrDefault(completedTaskId, new HashSet<>());
    }

    public void onTaskCompleted(String taskId) {
        AsyncTaskStatus taskStatus = asyncTaskManager.getTaskStatus(taskId);
        if (taskStatus == null || !taskStatus.isCompleted()) {
            throw new IllegalStateException("Task " + taskId + " is not completed");
        }

        Set<String> nextTasks = getNextTasks(taskId);
        for (String nextTaskId : nextTasks) {
            AsyncTaskStatus nextTaskStatus = asyncTaskManager.getTaskStatus(nextTaskId);
            if (nextTaskStatus == null) {
                continue; // Skip if next task doesn't exist
            }
            if (canExecute(nextTaskId)) {
                AsyncTaskStatus nextStatus = asyncTaskManager.getTaskStatus(nextTaskId);
                if ("PENDING".equals(nextStatus.getStatus())) {
                    try {
                        asyncTaskManager.updateTaskStatus(nextTaskId, "READY", "依赖任务已完成，准备执行");
                    } catch (IllegalStateException e) {
                        // Log error but continue processing other tasks
                        System.err.println("Failed to update task " + nextTaskId + ": " + e.getMessage());
                    }
                }
            }
        }
    }

    public void clearTaskDependencies(String taskId) {
        Set<String> dependencies = taskDependencies.remove(taskId);
        if (dependencies != null) {
            for (String dependencyId : dependencies) {
                Set<String> dependents = dependentTasks.get(dependencyId);
                if (dependents != null) {
                    dependents.remove(taskId);
                    if (dependents.isEmpty()) {
                        dependentTasks.remove(dependencyId);
                    }
                }
            }
        }
    }
}